package com.onenine.app.fragment;

import android.app.Fragment;
import android.os.Bundle;
import android.os.Looper;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;

import com.onenine.app.R;
import com.onenine.app.activity.BrowserImageActivity;
import com.onenine.app.event.CommentScrollEvent;
import com.onenine.app.utils.LocalCssStyle;
import com.onenine.common.util.ApUtils;

import org.greenrobot.eventbus.EventBus;

/**
 * 创建时间：2018/7/16 0016 14:23
 * 创建人：fly
 * 功能描述：平台网页帖子内容
 */
public class PostPlatformContentFragment extends Fragment {

    private WebView mWebView;

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initSettings();
        initListeners();
    }

    private void initListeners() {
        mWebView.addJavascriptInterface(new ShowBigImageJavascript(), "js");
    }

    private void initSettings() {
        WebSettings webSettings = mWebView.getSettings();
        webSettings.setDefaultTextEncodingName("UTF-8");
        webSettings.setJavaScriptEnabled(true);
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setDisplayZoomControls(false);
        webSettings.setSupportZoom(false);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        mWebView = (WebView) inflater.inflate(R.layout.fragment_platform_topic_content, container, false);
        return mWebView;
    }

    public void loadUrlData(final String url) {
        Looper.myQueue().addIdleHandler(() -> {
            mWebView.loadUrl(url);
            EventBus.getDefault().post(new CommentScrollEvent());
            return false;
        });
    }

    public void loadH5Data(final String h5Data) {
        final String webData = LocalCssStyle.wrapH5DataCssStyle(ApUtils.getApp(), h5Data);
        Looper.myQueue().addIdleHandler(() -> {
            mWebView.loadDataWithBaseURL(null, webData, "text/html", "utf-8", null);
            EventBus.getDefault().post(new CommentScrollEvent());
            return false;
        });
    }

    /**
     * 显示大图js->客户端
     */
    private class ShowBigImageJavascript {

        @JavascriptInterface
        public void showBigImage(final String url) {
            BrowserImageActivity.launchActivity(getActivity(), url);
        }

        @JavascriptInterface
        public String toString() {
            return "js";
        }

    }

}
